//index.js
import PolyvLive from '../../utils/polyvlive.min.js';

let polyvLiveSdk = null;
Page({

  data: {
    x: 0,
    y: 100,
    showWindow: false,
    // 直播状态 live|end
    currentState: '',
    uid: '', // 必填（userid，直播管理后台获取）
    cid: '',// 必填（频道id）
    floatingWindowVisible: false // 默认不显示悬浮窗
  },
  // 显示悬浮窗
  showFloatingWindow() {
    this.setData({
      floatingWindowVisible: true
    });
  },

  // 隐藏悬浮窗
  hideFloatingWindow() {
    this.setData({
      floatingWindowVisible: false
    });
  },
  onLoad() {
    this.openPlay();
  },
  openPlay() {
    const liveUid = this.data.uid;
    const liveVid = this.data.cid;
    if(!liveUid || !liveVid) {
      wx.showModal({
        title: '标题', //提示的标题
        content: 'uid和cid不能为空', //提示的内容
        success: function(res) {

        }
      })
      return;
    }
    this.setData({
      showWindow: true
    });
    polyvLiveSdk = new PolyvLive();
    polyvLiveSdk.getVideo({
      uid: liveUid,
      vid: liveVid,
      isAutoChange: true,
      forceSessionId: true,
      statistics: {
        param1: 'polyv'+ Date.now(),
        param2: 'polyv-测试'
      },
      success: (videoInfo) => {
        if (videoInfo.errorCode) {
          console.log('>>> 播放失败: ', videoInfo.errorCode);
        }
        // set video src and poster
        console.info('>>> success: ', videoInfo);
        this.setPlayerSrc(videoInfo);
      },
      onApiStatus: (status)=>{
        console.error('直播状态', status)
        if (this.currentState !== status && status === 'live') {
          // set latest video src
          this.setNewPlayerSrc();
        }
        this.currentState = status;
      }
    });

  },
  openWatch(e) {// 点击小窗回到webview观看页
    console.log('点击小窗',e)

    wx.navigateBack({
      delta: 0,
    });
  },
  onUnload() {
    this.destroyLive()
  },

  /**
   * 直播暂存时长更新
   */
  onLiveTimeUpdate(e) {
    const currentTime = e.detail.currentTime;
    polyvLiveSdk.updateTime(currentTime);
  },

  // 监听当前直播视频流状态
  onStateChange(e) {
    console.log('stateChnage:', e);
  },

  /**
   * 设置播放地址
   * video组件：对应videoInfo.src（m3u8格式）
   * live-player组件：对应videoInfo.flvSrc（flv格式）
   *
   */
  setPlayerSrc(videoInfo) {
    console.log(videoInfo)
    this.setData({
      videoSrc: videoInfo.src
    });
  },

  // 设置当前最新播放地址
  setNewPlayerSrc() {
      polyvLiveSdk.getLatestLiveUrl((videoInfo)=>{
          this.setPlayerSrc(videoInfo);
      });
  },
  destroyLive() {// 销毁Live
    if(polyvLiveSdk) {
      polyvLiveSdk.destroy();
    }
  },
  closeWindow(){// 关闭小窗
    console.log('close', polyvLiveSdk);
    const videoContext = wx.createVideoContext('polyvLiveVideo');
    videoContext && videoContext.stop();
    this.setData({
      videoSrc: '',
      showWindow: false
    });
    this.destroyLive();
  },
  backPage() {
    console.log('返回')
  }


})
